package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import jodd.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return true;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        //获取全部的商品
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        //获取商品id集合，此时为null,因为在转化的时候并没有设置
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        if (CollectionUtils.isEmpty(buyProductIds)) {
            // for (CartProductDto cartProductDto : cartProductDtoList) {
            //     buyProductIds.add(cartProductDto.getProductId());
            // }
            buyProductIds = cartProductDtoList.stream().map(u -> u.getProductId()).collect(Collectors.toList());
            //cartProductDtoList.stream().sorted(Comparator.comparing(CartProductDto::getProductId)).map(u -> u.getProductId()).collect(Collectors.toList());
        }
        //进行排序
        buyProductIds.sort(Long::compareTo);

        //锁住库存
        List<Stock> stockList = stockMapper.findStocksForUpdate(buyProductIds);

        //判断是否为空
        if (CollectionUtils.isEmpty(stockList)) {
            throw new BizException("库存未初始化!");
        }
        if (stockList.size() != buyProductIds.size()) {
            throw new BizException("部分商品库存未初始化！");
        }

        //扣减库存
        for (CartProductDto cartProductDto : cartProductDtoList) {

            @NotNull @Min(0) Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();
            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);
            stockMapper.updateStock(stock);
        }

        return true;
    }
}